﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using Grundy.Common;
using Grundy.CryptographicServices;
using System.Data.Entity;
using Grundy.Entity;
using Grundy.Message;

namespace Grundy.Administration.Web.Services
{
    public class NodeService
    {
        public EntitlementsDatabase Db { get; private set; }

        public NodeService()
        {
            Db = new EntitlementsDatabase("EntitlementsDatabase");
        }

        public NodeService(EntitlementsDatabase db)
        {
            Db = db;
        }

        public IQueryable<Node> GetNodes(int page = 1, int pageSize = 0)
        {
            if (page == 1 && pageSize == 0)
                return Db.Nodes.Include(i => i.Identifiers).OrderBy(i => i.Name);
            return Db.Nodes.Include(i => i.Identifiers).OrderBy(i => i.Name).Skip((page - 1) * pageSize).Take(pageSize);
        }

        public Node CreateNode(string name, IEnumerable<Identifier> identifiers)
        {
            var node = new Node {Name = name, Identifiers = new IdentifierCollection(identifiers)};
            Db.Nodes.Add(node);
            Db.SaveChanges();
            return node;
        }

        public IQueryable<Node> GetNodesStartingWithIdOrName(string term)
        {
            var results = ((IObjectContextAdapter)Db).ObjectContext.ExecuteStoreQuery<Node>("SELECT * FROM Nodes WHERE Id LIKE @prefix + '%' OR Name LIKE @prefix + '%'", new SqlParameter("prefix", term));
            return results.AsQueryable();
        }

        public IQueryable<LicenseEntitlement> GetLicensesForNodes(IEnumerable<Guid> nodeIds)
        {
            if (nodeIds.IsNullOrEmpty())
            {
                return new List<LicenseEntitlement>().AsQueryable();
            }
            var inString = string.Join(", ", nodeIds.Select(i => "'{0}'".FormatWith(i)));
            var leIds = ((IObjectContextAdapter)Db).ObjectContext.ExecuteStoreQuery<Guid>("SELECT Id FROM LicenseEntitlements WHERE Node_Id IN ({0})".FormatWith(inString));
            var licenseEntitlements = Db.LicenseEntitlements.Include(i => i.License).Where(i => leIds.Contains(i.Id));
            return licenseEntitlements;
        }
    }
}